package com.watson.juc.testlist;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author watson
 * @date 2021/7/30 10:52
 * @Description: TODO
 **/
public class SemaphoreDemo {
    public static void main(String[] args) {
        // 6车 3个停车位
        Semaphore semaphore = new Semaphore(3);
        for (int i = 1; i <= 6; i++) {
            //得到车位
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "得到车位");
                    //停车
                    TimeUnit.SECONDS.sleep(5);
                    System.out.println(Thread.currentThread().getName() + "离开");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //释放
                    semaphore.release();
                }

            }, String.valueOf(i)).start();
        }


    }
}
